package bill.study.concurrency.synchronizer.latch.javacip.chapter5;

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import bill.study.concurrency.patterns.producerconsumer.javacip.ch5.FileCrawler;

public class TestHarness {

	public static long timeTasks(int nThreads, final Runnable task)
			throws InterruptedException {

		final CountDownLatch startGate = new CountDownLatch(1);
		final CountDownLatch endGate = new CountDownLatch(nThreads);

		for (int i = 0; i < nThreads; i++) {
			Thread t = new Thread() {
				public void run() {
					try {
						startGate.await();
						try {
							task.run();
						} finally {
							endGate.countDown();
						}
					} catch (InterruptedException ie) {

					}
				}
			};
			t.start();

		}

		long start = System.nanoTime();
		startGate.countDown();
		endGate.await();
		long end = System.nanoTime();

		return end - start;

	}

	public static void main(String[] args) {
		FileCrawler crawler = new FileCrawler(new File("c:"), new FileFilter() {
			public boolean accept(File file) {
//				if(file.isFile() && file.getName().endsWith("java"))
				return true;
//				return false;
			}
		}, new LinkedBlockingQueue(100));
		try {
			long time = timeTasks(5, crawler);
			System.out.println("the average time is " + time/5);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
